/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

import './fontSize.css';

import {$getSelection, LexicalEditor} from 'lexical';
import * as React from 'react';
import {useCallback} from 'react';

import {$patchStyleText} from '@lexical/selection';

import DropDown, {DropDownItem} from '../../ui/DropDown';

function parseFontSize(input: string): [number, string] | null {
  const match = input.match(/^(\d+(?:\.\d+)?)(px|pt)$/);
  return match ? [Number(match[1]), match[2]] : null;
}

function normalizeToPx(fontSize: number, unit: string): number {
  return unit === 'pt' ? Math.round((fontSize * 4) / 3) : fontSize;
}

export function parseFontSizeForToolbar(input: string): string {
  const parsed = parseFontSize(input);
  if (!parsed) {
    return '';
  }

  const [fontSize, unit] = parsed;
  const fontSizePx = normalizeToPx(fontSize, unit);
  return `${fontSizePx}px`;
}

export function parseAllowedFontSize(input: string): string {
  const parsed = parseFontSize(input);
  if (!parsed) {
    return '';
  }

  const [fontSize, unit] = parsed;
  const fontSizePx = normalizeToPx(fontSize, unit);
  return input;
}

const FONT_SIZE_OPTIONS: [string, string][] = [
  ['12px', '12px'],
  ['13px', '13px'],
  ['14px', '14px'],
  ['15px', '默认字号'],
  ['16px', '16px'],
  ['19px', '19px'],
  ['22px', '22px'],
  ['24px', '24px'],
  ['29px', '29px'],
  ['32px', '32px'],
  ['40px', '40px'],
  ['48px', '48px'],
];

function dropDownActiveClass(active: boolean) {
  if (active) {
    return 'active dropdown-item-active';
  } else {
    return '';
  }
}

export default function FontSize({
  selectionFontSize,
  disabled,
  editor,
}: {
  selectionFontSize: string;
  disabled: boolean;
  editor: LexicalEditor;
}) {
  const handleClick = useCallback(
    (option: string) => {
      editor.update(() => {
        const selection = $getSelection();
        if (selection !== null) {
          $patchStyleText(selection, {
            'font-size': option,
          });
        }
      });
    },
    [editor],
  );

  // 将当前字体大小转换为带单位的显示值
  const currentFontSize = selectionFontSize ? `${selectionFontSize}px` : '15px';
  
  // 根据字体大小显示对应的标签
  const getDisplayLabel = (fontSize: string) => {
    return fontSize === '15px' ? '默认字号' : fontSize;
  };

  return (
    <DropDown
      disabled={disabled}
      buttonClassName="toolbar-item font-size"
      buttonLabel={getDisplayLabel(currentFontSize)}
      buttonAriaLabel="Formatting options for font size">
      {FONT_SIZE_OPTIONS.map(([option, text]) => (
        <DropDownItem
          className={`item ${dropDownActiveClass(currentFontSize === option)} fontsize-item`}
          onClick={() => handleClick(option)}
          key={option}>
          <span className="text">{text}</span>
        </DropDownItem>
      ))}
    </DropDown>
  );
}
